//
//  RFViewController.m
//  吃货·上海
//
//  Created by 高青松 on 15/11/25.
//  Copyright © 2015年 濮亚军. All rights reserved.
//

#import "RFViewController.h"
#import <BmobSDK/Bmob.h>
@interface RFViewController ()

// 手机注册
@property (nonatomic,strong)UILabel *phoneLabel;
@property (nonatomic,strong)UITextField *phoneTF;
@property (nonatomic,strong)UILabel *pwLabel;
@property (nonatomic,strong)UITextField *pwTF;
@property (nonatomic,strong)UILabel *cpwLabel;
@property (nonatomic,strong)UITextField *cpwTF;

@property (nonatomic,strong)UIButton *phoneBtn;


// 手机验证
@property (nonatomic,strong)UILabel *affirmLabel;
@property (nonatomic,strong)UITextField *affirmTF;
@property (nonatomic,strong)UIButton *affirmBtn;

@end

@implementation RFViewController
{
    BOOL timeStart;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [imageView setImage:[UIImage imageNamed:@"ch"]];
    [self.view addSubview:imageView];
    
    UIImageView *shaImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    shaImageView.backgroundColor = [UIColor blackColor];
    shaImageView.alpha = 0.3;
    [self.view addSubview:shaImageView];
    
    // 手机验证码
    self.phoneLabel = [[UILabel alloc]initWithFrame:CGRectMake((KScreenWidth-300)/2, KScreenHeight/4, 80, 30)];
    self.phoneLabel.backgroundColor = KColor;
    self.phoneLabel.layer.masksToBounds = YES;
    [self.phoneLabel.layer setCornerRadius:8];
    self.phoneLabel.text = @"手机号码";
    self.phoneLabel.textColor = [UIColor whiteColor];
    self.phoneLabel.font = [UIFont boldSystemFontOfSize:17];
    self.phoneLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.phoneLabel];
    
    self.phoneTF = [[UITextField alloc]initWithFrame:CGRectMake((KScreenWidth-300)/2+ 80, KScreenHeight/4, 220, 30)];
    self.phoneTF.layer.masksToBounds = YES;
    [self.phoneTF.layer setCornerRadius:8];
    self.phoneTF.backgroundColor = KMyColor;
    self.phoneTF.placeholder = @"请输入您的手机号码";
    self.phoneTF.clearsOnBeginEditing = YES;
    self.phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.phoneTF];
    
    
    // 密码校验
    self.pwLabel = [[UILabel alloc]initWithFrame:CGRectMake((KScreenWidth-300)/2, KScreenHeight/4+50, 80, 30)];
    self.pwLabel.text = @"密码";
    self.pwLabel.layer.masksToBounds = YES;
    [self.pwLabel.layer setCornerRadius:8];
    self.pwLabel.backgroundColor = KColor;
    self.pwLabel.textColor = [UIColor whiteColor];
    self.pwLabel.font = [UIFont boldSystemFontOfSize:17];
    self.pwLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.pwLabel];
    
    self.pwTF = [[UITextField alloc]initWithFrame:CGRectMake((KScreenWidth-300)/2+ 80, KScreenHeight/4+50, 220, 30)];
    self.pwTF.placeholder = @"请输入您的密码";
    self.pwTF.layer.masksToBounds = YES;
    [self.pwTF.layer setCornerRadius:8];
    self.pwTF.backgroundColor = KMyColor;
    self.pwTF.secureTextEntry = YES;
    self.pwTF.clearsOnBeginEditing = YES;
    self.pwTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.pwTF];
    
    // 密码确定
    self.cpwLabel = [[UILabel alloc]initWithFrame:CGRectMake((KScreenWidth-300)/2, KScreenHeight/4+100, 80, 30)];
    self.cpwLabel.text = @"确认密码";
    self.cpwLabel.layer.masksToBounds = YES;
    [self.cpwLabel.layer setCornerRadius:8];
    self.cpwLabel.backgroundColor = KColor;
    self.cpwLabel.textColor = [UIColor whiteColor];
    self.cpwLabel.font = [UIFont boldSystemFontOfSize:17];
    self.cpwLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.cpwLabel];
    
    self.cpwTF = [[UITextField alloc]initWithFrame:CGRectMake((KScreenWidth-300)/2+ 80, KScreenHeight/4+100, 220, 30)];
    self.cpwTF.placeholder = @"请再次输入您的密码";
    self.cpwTF.layer.masksToBounds = YES;
    [self.cpwTF.layer setCornerRadius:8];
    self.cpwTF.backgroundColor = KMyColor;
    self.cpwTF.secureTextEntry = YES;
    self.cpwTF.clearsOnBeginEditing = YES;
    self.cpwTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.cpwTF];
    
    
    self.phoneBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.phoneBtn.frame = CGRectMake((KScreenWidth - 120)/2 , KScreenHeight/4 + 150, 120, 30);
    // 获取注册码
    [self.phoneBtn addTarget:self action:@selector(phoneBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.phoneBtn.backgroundColor = [UIColor greenColor];
    self.phoneBtn.layer.masksToBounds = YES;
    [self.phoneBtn.layer setCornerRadius:8];
    [self.phoneBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.view addSubview:self.phoneBtn];
    
   // 确定验证码
    self.affirmLabel = [[UILabel alloc]initWithFrame:CGRectMake((KScreenWidth-300)/2, KScreenHeight/2+50, 80, 30)];
    self.affirmLabel.text = @"验证码";
    self.affirmLabel.textColor = [UIColor whiteColor];
    self.affirmLabel.layer.masksToBounds = YES;
    [self.affirmLabel.layer setCornerRadius:8];
    self.affirmLabel.backgroundColor = KColor;
    self.affirmLabel.font = [UIFont boldSystemFontOfSize:17];
    self.affirmLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.affirmLabel];
    
    self.affirmTF = [[UITextField alloc]initWithFrame:CGRectMake((KScreenWidth-300)/2+80, KScreenHeight/2+50, 220, 30)];
    self.affirmTF.placeholder = @"请输入您的验证码";
    self.affirmTF.layer.masksToBounds = YES;
    [self.affirmTF.layer setCornerRadius:8];
    self.affirmTF.backgroundColor = KMyColor;
    self.affirmTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.affirmTF];
    self.affirmBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.affirmBtn.frame = CGRectMake((KScreenWidth - 120)/2, KScreenHeight/2 + 100, 120, 30);
    // 确认验证码
    [self.affirmBtn addTarget:self action:@selector(affirmBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.affirmBtn.layer.masksToBounds = YES;
    [self.affirmBtn.layer setCornerRadius:8];
    self.affirmBtn.backgroundColor = [UIColor greenColor];
    [self.affirmBtn setTitle:@"确认验证码" forState:UIControlStateNormal];
    [self.view addSubview:self.affirmBtn];
}

// 获取验证码
- (void)phoneBtn:(UIButton *)btn
{
    if (self.phoneTF.text.length != 11) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您输入的手机号码不符合要求,请重新输入" delegate:nil
                                                 cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    if (self.pwTF.text.length < 6 ) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您输入的密码过短,请重新输入" delegate:nil
                                                 cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    if (![self.pwTF.text isEqualToString:self.cpwTF.text]) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您输入的两次密码不同,请重新输入" delegate:nil
                                                 cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    else
    {
    //获取手机号
    NSString *mobilePhoneNumber = self.phoneTF.text;
    
    //请求验证码
    [BmobSMS requestSMSCodeInBackgroundWithPhoneNumber:mobilePhoneNumber andTemplate:@"test" resultBlock:^(int number, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        } else {
            //获得smsID
            NSLog(@"sms ID：%d",number);
        }
    }];
//    [btn setTitle:@"已发送,请查收" forState:UIControlStateNormal];
    }
    
    // 60s 倒计时
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
    btn.userInteractionEnabled = NO;
    timeStart = YES;
}



- (void)timerFireMethod:(NSTimer *)theTimer

{
    
    NSDate *today = [NSDate date];    //得到当前时间
    
    NSDate *date = [NSDate dateWithTimeInterval:60 sinceDate:today];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    
    
    static int year;
    
    static int month;
    
    static int day;
    
    static int hour;
    
    static int minute;
    
    static int second;
    
    if(timeStart) {//从NSDate中取出年月日，时分秒，但是只能取一次
        
        year = [[dateString substringWithRange:NSMakeRange(0, 4)] intValue];
        
        month = [[dateString substringWithRange:NSMakeRange(5, 2)] intValue];
        
        day = [[dateString substringWithRange:NSMakeRange(8, 2)] intValue];
        
        hour = [[dateString substringWithRange:NSMakeRange(11, 2)] intValue];
        
        minute = [[dateString substringWithRange:NSMakeRange(14, 2)] intValue];
        
        second = [[dateString substringWithRange:NSMakeRange(17, 2)] intValue];
        
        timeStart= NO;
        
    }
    
    
    
    NSDateComponents *endTime = [[NSDateComponents alloc] init];    //初始化目标时间...
    
    [endTime setYear:year];
    
    [endTime setMonth:month];
    
    [endTime setDay:day];
    
    [endTime setHour:hour];
    
    [endTime setMinute:minute];
    
    [endTime setSecond:second];
    
    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象
    
    NSDate *todate = [cal dateFromComponents:endTime]; //把目标时间装载入date
    
    
    
    //用来得到具体的时差，是为了统一成北京时间
    
    unsigned int unitFlags = NSYearCalendarUnit| NSMonthCalendarUnit| NSDayCalendarUnit| NSHourCalendarUnit| NSMinuteCalendarUnit| NSSecondCalendarUnit;
    
    NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:todate options:0];
    
    NSString *fen = [NSString stringWithFormat:@"%ld", (long)[d minute]];
    
    if([d minute] < 10) {
        
        fen = [NSString stringWithFormat:@"0%ld",(long)[d minute]];
        
    }
    
    NSString *miao = [NSString stringWithFormat:@"%ld", (long)[d second]];
    
    if([d second] < 10) {
        
        miao = [NSString stringWithFormat:@"0%ld",(long)[d second]];
        
    }
    
    
    
    if([d second] > 0) {
        
        //计时尚未结束，do_something
        [self.phoneBtn setTitle:[NSString stringWithFormat:@"%lds后重新获取",[d second]] forState:UIControlStateNormal];
        
    } else if([d second] == 0) {  
        
        self.phoneBtn.userInteractionEnabled = YES;
        
    } else{
        [self.phoneBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [theTimer invalidate];
        
    }
    
    
    
}

// 验证验证码
- (void)affirmBtn:(UIButton *)btn
{
    //获取手机号、验证码
    NSString *mobilePhoneNumber = self.phoneTF.text;
    NSString *smsCode = self.affirmTF.text;
    
    //验证
    [BmobSMS verifySMSCodeInBackgroundWithPhoneNumber:mobilePhoneNumber andSMSCode:smsCode resultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            
            //往_User表添加验证通过的手机用户
            BmobUser *bUser = [[BmobUser alloc]init];
            [bUser setUsername:self.phoneTF.text];
            [bUser setPassword:self.pwTF.text];
            
            
//            [BmobUser loginWithUsernameInBackground:self.phoneTF.text
//                                           password:self.pwTF.text];
            [bUser signUpInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful)
                {
                    NSLog(@"成功");
                }
                else
                {
                    NSLog(@"error =%@",error.description);
                }
            }];
            NSLog(@"%@",@"验证成功，可执行用户请求的操作");
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册成功！！！请返回登陆界面登陆" delegate:nil
             cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        } else {
            NSLog(@"%@",error);
        }
    }];
}

// 回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    for (UIView *view in self.view.subviews) {
        [view resignFirstResponder];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
